package cn.li.security.config;


import cn.li.security.json.JSONAuthenticationConfiguration;
import cn.li.security.json.handle.AccessDeniedJSONHandler;
import cn.li.security.json.handle.AuthenticationFailJSONHandler;
import cn.li.security.json.handle.AuthenticationSuccessJSONHandler;
import cn.li.security.json.handle.NoneAuthenticationJSONHandler;
import cn.li.security.jwt.JwtAuthenticationConfiguration;
import cn.li.security.jwt.JwtAuthenticationProvider;
import cn.li.security.jwt.JwtAuthenticationSuccessHandler;
import cn.li.security.jwt.service.DefaultJwtService;
import cn.li.security.jwt.service.IJwtService;
import cn.li.security.sms.ISmsUserDetailService;
import cn.li.security.sms.SmsAuthenticationSecurityConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)      //这边开启基于方法的注解
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //注入我们指定一个的userDetail
    @Autowired
    public UserDetailsService userDetailsService;
    @Autowired
    private ObjectMapper objectMapper;

    @Bean
    public IJwtService jwtService(){
        return new DefaultJwtService();
    }


    @Bean
    public JSONAuthenticationConfiguration jsonAuthenticationConfiguration(){
        JSONAuthenticationConfiguration config =  new JSONAuthenticationConfiguration(objectMapper);
        //将JSON登陆适配成jwt
        config.setAuthenticationSuccessHandler(new JwtAuthenticationSuccessHandler(jwtService(),objectMapper));
        return config;
    }


    @Bean
    public JwtAuthenticationConfiguration jwtAuthenticationConfiguration(){
        JwtAuthenticationConfiguration config =  new JwtAuthenticationConfiguration(objectMapper,userDetailsService,jwtService());
        return config;
    }


    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint(){
        return new NoneAuthenticationJSONHandler(objectMapper);
    }

    @Bean
    public AccessDeniedHandler accessDeniedJSONHandler(){
        return new AccessDeniedJSONHandler(objectMapper);
    }
    @Autowired
    public ISmsUserDetailService smsUserDetailsService;
    @Bean
    public SmsAuthenticationSecurityConfig smsAuthenticationSecurityConfig(){
        SmsAuthenticationSecurityConfig s =  new SmsAuthenticationSecurityConfig(smsUserDetailsService,objectMapper);
        s.setSuccessHandler(new JwtAuthenticationSuccessHandler(jwtService(),objectMapper));
        return s;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()      // 下面开始配置权限
                .antMatchers("/admin/**").hasAnyRole("admin")//匹配路径，并要求权限
                .antMatchers("/user/**").hasAnyRole("user")//匹配路径，并要求权限
                .antMatchers("/account/**").authenticated()        //账户信息，只要有登陆即可
                .anyRequest().permitAll() //其他的请求都不需要登陆，这里把权限交给了
            .and()
                .apply(smsAuthenticationSecurityConfig())
            .and()
                //加入配置jwt的filter等，用于解析header中的Authorization
                .apply(jwtAuthenticationConfiguration() )
            .and()
                .apply(jsonAuthenticationConfiguration())
            .and()
                .exceptionHandling()        //对exception进行自定义Handle
                .authenticationEntryPoint(authenticationEntryPoint())//把自定义的接口配置上去
                .accessDeniedHandler(accessDeniedJSONHandler())//自定义拒绝访问提示
        ;
        http.csrf().disable();
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder())
        ;
    }
}
